package org.yzh.scheduler.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.sample.commons.io.FileUtils;
import org.sample.commons.net.HttpUtils;
import org.sample.model.APIResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yzh.scheduler.model.vo.LogKey;
import org.yzh.scheduler.service.JobLogService;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

@ApiResponses(value = {
        @ApiResponse(code = 400, message = "请求参数有误", response = APIResult.class),
        @ApiResponse(code = 500, message = "服务器异常", response = APIResult.class)}
)
@Api(description = "任务回调API")
@RequestMapping("callback")
@RestController
public class CallbackController {

    @Autowired
    private JobLogService jobLogService;

    @ApiOperation(value = "callback")
    @RequestMapping(value = "{key}", method = {RequestMethod.GET, RequestMethod.POST})
    public void callback(@PathVariable String key, HttpServletRequest request) {
        LogKey logKey = jobLogService.parseKey(key);
        if (logKey == null)
            return;

        StringBuilder message = new StringBuilder(1024);

        try (BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                message.append(line);
                message.append(FileUtils.Separator);
            }
        } catch (Exception e) {
        }

        jobLogService.callback(logKey, message.toString());
    }

    /**
     * 客户端例子，对于任务执行较满的接口建议任务结果异步回调通知
     */
    @ApiOperation(value = "test")
    @RequestMapping(value = "test", method = {RequestMethod.GET, RequestMethod.POST})
    public APIResult test(@RequestParam(required = false) String callbackUrl) {
        new Thread(() -> {
            try {
                //执行任务中...
                Thread.sleep(3000L);

                //通知任务调度系统执行状态
                if (callbackUrl != null)
                    HttpUtils.doPost(callbackUrl, "SUCCESS");
            } catch (Exception e) {
            }
        }).start();

        //立即返回任务触发状态
        return new APIResult();
    }
}